package org.makcro.sms.services.chat.web.client.mvc.view;

import java.util.List;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.widgets.main.MessagesTabItem;
import org.makcro.sms.services.chat.web.client.widgets.main.NewMessagesPanel;
import org.makcro.sms.services.chat.web.shared.dto.QuestionDto;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.core.Template;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Params;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.google.gwt.dom.client.Document;

public class NewMessagesView extends View {

	private Template windowTitleTemplate = new Template( "Chat({numberOfNewMessages})" );
	private NewMessagesPanel newMessagesPanel;

	public NewMessagesView(Controller controller) {
		super(controller);

		newMessagesPanel = new NewMessagesPanel();
	}

	@Override
	protected void initialize() {
		super.initialize();
	}

	@Override
	protected void handleEvent(AppEvent event) {
		EventType type = event.getType();

		if (type == AppEvents.LoginSuccessful) {
			onInit(event);
		}

		if (type == AppEvents.NewQuestionsFound) {
			onNewQuestionsFound(event);
		}

	}

	private void onInit(AppEvent event) {

		BorderLayoutData layoutData = new BorderLayoutData(LayoutRegion.CENTER);
		layoutData.setCollapsible(false);
		
//		layoutData.setMinSize(400);
		layoutData.setSize(0.5f);
//		layoutData.setSplit(true);
//		layoutData.setFloatable( true);
		
		MessagesTabItem messagesTab = Registry.get(Constants.Ui.MESSAGES_TAB_ITEM);
		messagesTab.add(newMessagesPanel, layoutData);
		messagesTab.layout();

	}
	
	private void onNewQuestionsFound(AppEvent event) {
		// bind new messages to new messages grid
		ListStore<QuestionDto> store = newMessagesPanel.getStore();
		
		store.removeAll();
		
		List<QuestionDto> questions = event.<List<QuestionDto>>getData();
		if (questions.size() > 0) {
			store.add( questions );
			Info.display( "Obavestenje", "Nove poruke dostupne" );
		}
		
		// update window title
		String windowTitle = this.windowTitleTemplate.applyTemplate( new Params( "numberOfNewMessages", questions.size() ) );
		Document.get().setTitle( windowTitle );
	}

}
